from fastapi import FastAPI
import logging
import os
from fastapi.middleware.cors import CORSMiddleware

from .routers.servers import router as servers_router
from .routers.ws import router as ws_router
from .routers.logs import router as logs_router
from .routers.settings import router as settings_router


def create_app() -> FastAPI:
    # 基础日志配置，可通过环境变量 APP_LOG_LEVEL 控制（DEBUG/INFO/WARNING/...）
    log_level_name = os.getenv("APP_LOG_LEVEL", "INFO").upper()
    log_level = getattr(logging, log_level_name, logging.INFO)
    logging.basicConfig(
        level=log_level,
        format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        force=True,  # 覆盖可能由 Uvicorn 预先设置的处理器
    )
    # 在 DEBUG 模式下，对核心模块提升到 DEBUG，便于排查
    if log_level <= logging.DEBUG:
        logging.getLogger("backend.app.routers.ws").setLevel(logging.DEBUG)
        logging.getLogger("backend.app.services.ssh").setLevel(logging.DEBUG)
        logging.getLogger("paramiko").setLevel(logging.INFO)
    app = FastAPI(title="AI Server Monitor", version="0.1.0")

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    app.include_router(servers_router, prefix="/api/servers", tags=["servers"])
    app.include_router(logs_router, prefix="/api/logs", tags=["logs"])
    app.include_router(ws_router, tags=["websocket"])
    app.include_router(settings_router, prefix="/api/settings", tags=["settings"])

    @app.get("/health")
    def health() -> dict:
        return {"status": "ok"}

    return app


app = create_app()

